File size: 23,803 Bytes
ce35fa9
83954ae
ce35fa9
83954ae
ce35fa9
 
 
83954ae
ce35fa9
 
 
 
 
83954ae
ce35fa9
 
adda1ae
ce35fa9
83954ae
 
 
ce35fa9
 
 
 
 
 
 
 
 
 
83954ae
 
ce35fa9
 
 
 
 
 
adda1ae
 
 
ce35fa9
 
 
 
9a6952b
 
 
ce35fa9
de71b62
 
 
 
 
33233d1
 
 
 
 
ce35fa9
83954ae
 
 
 
 
 
 
 
 
ce35fa9
83954ae
 
 
 
 
 
 
ce35fa9
 
33233d1
 
 
 
 
adda1ae
 
bdd9d09
 
 
 
ce35fa9
 
bdd9d09
 
 
 
83954ae
bdd9d09
 
 
 
83954ae
adda1ae
ce35fa9
adda1ae
 
 
83954ae
adda1ae
 
bdd9d09
ce35fa9
 
83954ae
 
ce35fa9
 
83954ae
ce35fa9
 
 
adda1ae
ce35fa9
 
 
 
 
 
adda1ae
 
 
ce35fa9
 
83954ae
ce35fa9
33233d1
ce35fa9
d330331
ce35fa9
 
 
 
 
83954ae
ce35fa9
 
 
 
d330331
ce35fa9
adda1ae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83954ae
ce35fa9
 
 
adda1ae
 
 
ce35fa9
 
 
 
 
 
bdd9d09
 
d330331
ce35fa9
 
 
83954ae
ce35fa9
 
 
 
 
 
83954ae
bdd9d09
ce35fa9
83954ae
ce35fa9
83954ae
ce35fa9
 
 
 
 
bdd9d09
ce35fa9
 
 
 
adda1ae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ce35fa9
 
 
 
83954ae
ce35fa9
 
 
 
9a6952b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ce35fa9
 
83954ae
9a6952b
 
83954ae
ce35fa9
 
 
de71b62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33233d1
de71b62
 
 
 
 
 
 
 
 
 
 
 
 
33233d1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83954ae
 
 
ce35fa9
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
import os
import json
import httpx
import google.generativeai as genai
from dotenv import load_dotenv
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from fastapi.responses import FileResponse
from pydantic import BaseModel

load_dotenv()

GEMINI_API_KEY = os.getenv("GEMINI_API_KEY", "")
PATENTSVIEW_API_KEY = os.getenv("PATENTSVIEW_API_KEY", "")
PATENTSVIEW_BASE = "https://search.patentsview.org/api/v1/patent"
PATENTSVIEW_CITATIONS = "https://search.patentsview.org/api/v1/patent/us_patent_citation"

if GEMINI_API_KEY:
    genai.configure(api_key=GEMINI_API_KEY)

app = FastAPI(title="Eddison Intelligence API")

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_methods=["*"],
    allow_headers=["*"],
)


# ── Request / Response Models ────────────────────────────────────────────────

class AnalyzeRequest(BaseModel):
    text: str

class SearchRequest(BaseModel):
    keywords: list[str]
    kind_codes: list[str] = []
    cpc_codes: list[str] = []
    sort_by: str = "date"
    after: list | None = None

class ClaimRequest(BaseModel):
    invention_text: str
    prior_art: list[dict]
    improvement_focus: str | None = None
    previous_claims: str | None = None
    analysis_feedback: dict | None = None

class ClaimAnalysisRequest(BaseModel):
    claims: str
    invention_text: str
    prior_art: list[dict]

class EvaluatePatentRequest(BaseModel):
    invention_text: str
    patent: dict
    decomposition: dict


# ── Helpers ──────────────────────────────────────────────────────────────────

async def call_gemini(system: str, user_message: str) -> str:
    if not GEMINI_API_KEY:
        raise HTTPException(503, "GEMINI_API_KEY not configured β€” get a free key at https://aistudio.google.com/apikey")
    try:
        model = genai.GenerativeModel(
            model_name="gemini-2.0-flash",
            system_instruction=system,
        )
        response = await model.generate_content_async(user_message)
        return response.text
    except Exception as e:
        error_msg = str(e)
        if "RESOURCE_EXHAUSTED" in error_msg or "429" in error_msg:
            raise HTTPException(429, "Gemini free-tier quota exceeded. Try again later or check https://aistudio.google.com for limits.")
        raise HTTPException(502, f"Gemini API error: {error_msg}")


def clean_json(raw: str) -> str:
    """Strip markdown fences from Gemini JSON responses."""
    return raw.replace("```json", "").replace("```", "").strip()


def build_patentsview_query(keywords: list[str], kind_codes: list[str], cpc_codes: list[str]) -> dict:
    """Build a PatentsView API query from keywords, kind codes, and CPC codes.

    Each keyword phrase is matched with _text_all (all words must appear)
    against title OR abstract. A patent matches if ANY keyword phrase hits.
    """
    keyword_clauses = []
    for kw in keywords:
        keyword_clauses.append({"_or": [
            {"_text_all": {"patent_abstract": kw}},
            {"_text_all": {"patent_title": kw}},
        ]})

    if len(keyword_clauses) > 1:
        text_clause = {"_or": keyword_clauses}
    else:
        text_clause = keyword_clauses[0]

    clauses = [text_clause]
    if kind_codes:
        clauses.append({"wipo_kind": kind_codes})
    if cpc_codes:
        clauses.append({"cpc_at_issue.cpc_group_id": cpc_codes})

    if len(clauses) > 1:
        return {"_and": clauses}
    return text_clause


# ── Endpoints ────────────────────────────────────────────────────────────────

@app.post("/api/analyze")
async def analyze_invention(req: AnalyzeRequest):
    """Step 1: Extract keywords and suggest kind codes from an invention description."""
    system_prompt = """You are a USPTO patent expert. Given an invention description, extract:
1. 8-12 specific technical keywords/phrases for prior art search (precise, domain-specific)
2. 4-6 relevant USPTO Kind Codes with a one-line reason each
3. 3-5 relevant CPC (Cooperative Patent Classification) codes, e.g. G06F40/30, G06N20/00, with a one-line reason each

Respond ONLY with valid JSON in this exact format, no markdown:
{
  "keywords": ["keyword1", "keyword2"],
  "kindCodes": [
    {"code": "A1", "label": "Published Application", "reason": "relevant because..."}
  ],
  "cpcCodes": [
    {"code": "G06F40/30", "reason": "relevant because..."}
  ]
}"""
    raw = await call_gemini(system_prompt, f"Invention: {req.text}")
    try:
        parsed = json.loads(clean_json(raw))
    except json.JSONDecodeError:
        raise HTTPException(502, "Failed to parse Gemini response as JSON")
    return parsed


@app.post("/api/search")
async def search_prior_art(req: SearchRequest):
    """Step 2: Search PatentsView for real prior art matching keywords."""
    if not req.keywords:
        raise HTTPException(400, "At least one keyword is required")

    if not PATENTSVIEW_API_KEY:
        raise HTTPException(503, "PatentsView API key not configured. Add PATENTSVIEW_API_KEY to your .env file β€” request one at https://patentsview.org/apis/keyrequest")

    query = build_patentsview_query(req.keywords, req.kind_codes, req.cpc_codes)

    fields = [
        "patent_id", "patent_title", "patent_abstract", "patent_date",
        "patent_type", "wipo_kind",
        "assignees.assignee_organization",
        "cpc_at_issue.cpc_group_id", "cpc_at_issue.cpc_group",
    ]
    if req.sort_by == "citations":
        fields.append("patent_num_times_cited_by_us_patents")

    sort = (
        [{"patent_num_times_cited_by_us_patents": "desc"}, {"patent_id": "asc"}]
        if req.sort_by == "citations"
        else [{"patent_date": "desc"}, {"patent_id": "asc"}]
    )
    options = {"size": 25}
    if req.after:
        options["after"] = req.after

    headers = {"X-Api-Key": PATENTSVIEW_API_KEY, "Content-Type": "application/json"}
    params = {
        "q": query,
        "f": fields,
        "s": sort,
        "o": options,
    }

    async with httpx.AsyncClient(timeout=30) as client:
        resp = await client.post(PATENTSVIEW_BASE, headers=headers, json=params)

    if resp.status_code != 200:
        reason = resp.headers.get("X-Status-Reason", resp.text[:500])
        print(f"[PatentsView] HTTP {resp.status_code}: {reason}")
        raise HTTPException(502, f"PatentsView API error (HTTP {resp.status_code}): {reason}")

    data = resp.json()
    patents = data.get("patents", [])

    results = []
    for p in patents:
        assignee = "Unknown"
        assignees = p.get("assignees", [])
        if assignees and assignees[0].get("assignee_organization"):
            assignee = assignees[0]["assignee_organization"]

        cpcs = p.get("cpc_at_issue", [])
        cpc_str = cpcs[0]["cpc_group_id"] if cpcs else ""

        year = p.get("patent_date", "")[:4]

        results.append({
            "patentNumber": f"US{p.get('patent_id', '')}",
            "title": p.get("patent_title", ""),
            "assignee": assignee,
            "year": int(year) if year.isdigit() else 0,
            "kindCode": p.get("wipo_kind", ""),
            "abstract": p.get("patent_abstract", "")[:500],
            "cpc": cpc_str,
        })

    last = patents[-1] if patents else None
    after_cursor = None
    if last and len(patents) >= 25:
        if req.sort_by == "citations":
            after_cursor = [last.get("patent_num_times_cited_by_us_patents") or 0, last.get("patent_id")]
        else:
            after_cursor = [last.get("patent_date", ""), last.get("patent_id")]

    return {
        "results": results,
        "source": "patentsview",
        "total": data.get("total_hits", len(results)),
        "after": after_cursor,
    }


@app.get("/api/patent/{patent_id}/citations")
async def get_patent_citations(patent_id: str):
    """Fetch patents that cite this one (forward) and patents this one cites (backward)."""
    if not PATENTSVIEW_API_KEY:
        raise HTTPException(503, "PatentsView API key not configured")
    pid = patent_id.replace("US", "").replace(",", "").replace(" ", "").strip()
    if not pid or not pid.replace("0", ""):
        raise HTTPException(400, "Invalid patent ID")

    headers = {"X-Api-Key": PATENTSVIEW_API_KEY, "Content-Type": "application/json"}
    citing = []
    cited = []

    async with httpx.AsyncClient(timeout=30) as client:
        resp_forward = await client.post(
            PATENTSVIEW_CITATIONS,
            headers=headers,
            json={
                "q": {"citation_patent_id": pid},
                "f": ["patent_id"],
                "o": {"size": 10},
            },
        )
        if resp_forward.status_code == 200:
            data = resp_forward.json()
            for r in data.get("us_patent_citations", []):
                citing.append({"patent_id": r.get("patent_id", "")})

        resp_backward = await client.post(
            PATENTSVIEW_CITATIONS,
            headers=headers,
            json={
                "q": {"patent_id": pid},
                "f": ["citation_patent_id"],
                "o": {"size": 10},
            },
        )
        if resp_backward.status_code == 200:
            data = resp_backward.json()
            for r in data.get("us_patent_citations", []):
                cited.append({"patent_id": r.get("citation_patent_id", "")})

    return {"citing": citing, "cited": cited}


@app.post("/api/generate-claim")
async def generate_claim(req: ClaimRequest):
    """Step 3: Draft patent claims based on invention and approved prior art."""
    prior_art_summary = "\n".join(
        f"- {p.get('patentNumber', 'N/A')}: \"{p.get('title', '')}\" ({p.get('assignee', '')}, {p.get('year', '')}): {p.get('abstract', '')}"
        for p in req.prior_art
    )

    if req.improvement_focus and req.previous_claims and req.analysis_feedback:
        dimension_labels = {
            "specificity": "specificity (how precise and well-defined the claim elements are)",
            "protection": "protection scope (how broad the coverage is without being vulnerable to invalidation)",
            "infringements": "infringement potential (how commercially relevant and broadly applicable the claims are)",
        }
        dim_label = dimension_labels.get(req.improvement_focus, req.improvement_focus)
        fb = req.analysis_feedback
        bullets = "\n".join(f"- {b}" for b in fb.get("bullets", []))

        system_prompt = f"""You are a senior USPTO patent attorney. Rewrite the following patent claims to specifically improve their {dim_label}.

The previous analysis rated this dimension as: {fb.get('rating', 'Unknown')}
Assessment: {fb.get('summary', '')}
Key issues identified:
{bullets}

IMPORTANT INSTRUCTIONS:
- Rewrite ALL claims (independent and dependent) to address the identified weaknesses
- Maintain proper patent claim language (wherein, comprising, wherein said...)
- Keep the same structure: 1 independent claim + 3 dependent claims
- Preserve the claims' strengths in other dimensions while improving {req.improvement_focus}
- Number each claim. Be precise and technically accurate.
- Distinguish from the provided prior art."""

        user_msg = (
            f"Previous Claims to Improve:\n{req.previous_claims}\n\n"
            f"Invention: {req.invention_text}\n\n"
            f"Prior Art to distinguish from:\n{prior_art_summary}\n\n"
            f"Rewrite the claims with improved {req.improvement_focus}."
        )
    else:
        system_prompt = """You are a senior USPTO patent attorney. Write a professional first-draft patent claim set.
Format: 1 independent claim + 3 dependent claims. Use proper patent claim language (wherein, comprising, wherein said...).
Number each claim. Be precise and technically accurate. Distinguish from the provided prior art."""

        user_msg = f"Invention: {req.invention_text}\n\nPrior Art to distinguish from:\n{prior_art_summary}\n\nDraft the claim set."

    claim_text = await call_gemini(system_prompt, user_msg)
    return {"claims": claim_text.strip()}


@app.post("/api/analyze-claim")
async def analyze_claim(req: ClaimAnalysisRequest):
    """Analyze generated patent claims for specificity, protection scope, and potential infringements."""
    prior_art_summary = "\n".join(
        f"- {p.get('patentNumber', 'N/A')}: \"{p.get('title', '')}\" ({p.get('assignee', '')}, {p.get('year', '')}): {p.get('abstract', '')}"
        for p in req.prior_art
    )

    system_prompt = """You are a senior patent litigation attorney and patent prosecution strategist with 20+ years of experience. Analyze the given patent claims in the context of the invention description and relevant prior art.

Evaluate three dimensions:

1. SPECIFICITY β€” How specific and well-defined are the claim elements compared to the prior art? Consider whether the claims use precise technical language, clearly define boundaries, and differentiate from existing patents. Rate as "High" (claims are precisely scoped with clear technical boundaries), "Medium" (claims have reasonable specificity but some terms are broad), or "Low" (claims are vague or overlap significantly with prior art language).

2. PROTECTION SCOPE β€” How broad or narrow is the protection these claims would provide? Consider the independent claim's reach, whether dependent claims meaningfully narrow scope, and whether the claims cover the core inventive concept without being so broad as to be vulnerable to invalidation. Rate as "Broad" (wide protection covering many implementations), "Moderate" (balanced coverage of the inventive concept), or "Narrow" (limited to a very specific implementation).

3. POTENTIAL INFRINGEMENTS β€” What types of existing or future products, methods, systems, or services might fall within the scope of these claims? Consider both literal infringement and doctrine-of-equivalents scenarios. Rate the commercial relevance as "High" (large market, many potential infringers), "Medium" (niche market or moderate number of potential infringers), or "Low" (very narrow applicability).

Respond ONLY with valid JSON in this exact format, no markdown fences:
{
  "specificity": {
    "rating": "High or Medium or Low",
    "summary": "One sentence summarizing the specificity assessment.",
    "bullets": ["First key observation", "Second key observation", "Third key observation"]
  },
  "protection": {
    "rating": "Broad or Moderate or Narrow",
    "summary": "One sentence summarizing the protection scope.",
    "bullets": ["First key observation", "Second key observation", "Third key observation"]
  },
  "infringements": {
    "rating": "High or Medium or Low",
    "summary": "One sentence summarizing potential infringement landscape.",
    "bullets": ["First category of potentially infringing products/methods", "Second category", "Third category"]
  }
}"""

    user_msg = f"Patent Claims to Analyze:\n{req.claims}\n\nInvention Description:\n{req.invention_text}\n\nRelevant Prior Art:\n{prior_art_summary}\n\nProvide your structured analysis."

    raw = await call_gemini(system_prompt, user_msg)
    try:
        parsed = json.loads(clean_json(raw))
    except json.JSONDecodeError:
        raise HTTPException(502, "Failed to parse Gemini claim analysis response as JSON")

    for key in ("specificity", "protection", "infringements"):
        if key not in parsed:
            raise HTTPException(502, f"Gemini response missing '{key}' section")
        section = parsed[key]
        if "rating" not in section or "summary" not in section or "bullets" not in section:
            raise HTTPException(502, f"Gemini response '{key}' section missing required fields")

    return parsed


# ── USPTO 7-Step Methodology Endpoints ────────────────────────────────────────

SYSTEM_DECOMPOSE = """You are a USPTO patent search expert. Given an invention description, perform two tasks:

TASK 1 β€” DECOMPOSE THE INVENTION
Extract and categorize:
- core_features: 3-5 core technical features that define the invention's novelty
- supporting_features: 2-4 supporting/secondary features that enable or enhance the core
- claimed_improvements: 1-3 specific technical improvements over existing solutions
- components: hardware/software interaction components involved

TASK 2 β€” SYNONYM EXPANSION
For EACH core_feature, generate:
- technical_synonyms: 2-3 precise technical synonyms (no marketing terms)
- industry_terms: 1-2 industry-specific terminology equivalents
- broader: 1 broader/more generic term
- narrower: 1 narrower/more specific term

From the decomposition and synonyms, also extract:
- keywords: 8-12 specific search keywords/phrases combining core features and their best synonyms
- kindCodes: 4-6 relevant USPTO Kind Codes with label and one-line reason

Respond ONLY with valid JSON, no markdown fences:
{
  "decomposition": {
    "core_features": ["feature1", "feature2"],
    "supporting_features": ["feat1", "feat2"],
    "claimed_improvements": ["improvement1"],
    "components": ["component1", "component2"]
  },
  "synonyms": {
    "feature name here": {
      "technical_synonyms": ["syn1", "syn2"],
      "industry_terms": ["term1"],
      "broader": "broader_term",
      "narrower": "narrower_term"
    }
  },
  "keywords": ["keyword1", "keyword2"],
  "kindCodes": [
    {"code": "A1", "label": "Published Application", "reason": "relevant because..."}
  ]
}"""

SYSTEM_CPC_BOOLEAN = """You are a USPTO patent classification and search strategy expert. Given an invention description and its decomposed features, perform two tasks:

TASK 1 β€” CPC CLASSIFICATION
Identify likely Cooperative Patent Classification codes:
- 2-3 primary CPC codes most directly relevant to the invention, with explanation
- 2-3 secondary/adjacent CPC codes, with explanation
Prioritize AI, data processing, memory, or hardware interaction classes when applicable.

TASK 2 β€” BOOLEAN SEARCH STRINGS
Construct three tiers of search queries:
- broad: 2 queries combining 1 core feature OR its synonyms β€” maximum recall
- intermediate: 2 queries combining 2 core features AND 1 secondary feature β€” balanced
- examiner: 2 queries using specific technical terms with classification restrictions β€” maximum precision

Each query must use Boolean operators (AND/OR), include parentheses, and combine 1-2 core features + 1 secondary feature. Avoid over-constraining.

For each query, also extract keyword_sets: arrays of keyword phrases suitable for PatentsView API full-text search.

Respond ONLY with valid JSON, no markdown fences:
{
  "cpcCodes": [
    {"code": "G06F40/30", "type": "primary", "reason": "relevant because..."},
    {"code": "H04L67/00", "type": "secondary", "reason": "relevant because..."}
  ],
  "booleanQueries": [
    {
      "level": "broad",
      "label": "Broad β€” Maximum Recall",
      "query": "(term1 OR term2) AND (term3)",
      "keyword_sets": ["term1 term3", "term2 term3"]
    }
  ]
}"""

SYSTEM_EVALUATE = """You are a USPTO patent examiner performing a prior art comparison. Given an invention and a prior art patent, evaluate using the standard examiner comparison framework.

For each core feature of the invention, determine:
- disclosed: Does the prior art explicitly disclose this feature? ("yes", "partial", or "no")
- equivalent: Does it describe an equivalent structure or method? ("yes", "partial", or "no")
- same_solution: Does it achieve the same technical solution? ("yes", "partial", or "no")
- problem_only: Does it merely describe the problem without the solution? ("yes" or "no")

Also provide:
- overlap_summary: One sentence on how much this prior art overlaps with the invention
- threat_level: "high" (blocks patentability), "medium" (requires claim narrowing), or "low" (distinguishable)
- distinguishing_features: list of invention features NOT found in this prior art

Respond ONLY with valid JSON, no markdown fences:
{
  "feature_comparison": [
    {
      "feature": "the core feature text",
      "disclosed": "yes",
      "equivalent": "partial",
      "same_solution": "no",
      "problem_only": "no"
    }
  ],
  "overlap_summary": "...",
  "threat_level": "medium",
  "distinguishing_features": ["feature1", "feature2"]
}"""


@app.post("/api/analyze-deep")
async def analyze_deep(req: AnalyzeRequest):
    """USPTO 7-Step: Decompose invention, expand synonyms, classify CPC, and build search queries."""
    # Call 1: Decomposition + Synonyms + Keywords + Kind Codes (Steps 1-2)
    raw1 = await call_gemini(SYSTEM_DECOMPOSE, f"Invention: {req.text}")
    try:
        parsed1 = json.loads(clean_json(raw1))
    except json.JSONDecodeError:
        raise HTTPException(502, "Failed to parse decomposition response as JSON")

    # Call 2: CPC Classification + Boolean Queries (Steps 3-4)
    decomp_context = json.dumps(parsed1.get("decomposition", {}))
    synonym_context = json.dumps(parsed1.get("synonyms", {}))
    context_msg = (
        f"Invention: {req.text}\n\n"
        f"Decomposition:\n{decomp_context}\n\n"
        f"Core feature synonyms:\n{synonym_context}"
    )
    try:
        raw2 = await call_gemini(SYSTEM_CPC_BOOLEAN, context_msg)
        parsed2 = json.loads(clean_json(raw2))
    except json.JSONDecodeError:
        # If Call 2 fails, return Call 1 results with empty CPC/boolean fields
        parsed2 = {"cpcCodes": [], "booleanQueries": []}
    except HTTPException:
        parsed2 = {"cpcCodes": [], "booleanQueries": []}

    return {
        "decomposition": parsed1.get("decomposition"),
        "synonyms": parsed1.get("synonyms"),
        "keywords": parsed1.get("keywords", []),
        "kindCodes": parsed1.get("kindCodes", []),
        "cpcCodes": parsed2.get("cpcCodes", []),
        "booleanQueries": parsed2.get("booleanQueries", []),
    }


@app.post("/api/evaluate-patent")
async def evaluate_patent(req: EvaluatePatentRequest):
    """USPTO Step 6: Examiner-level comparison of a prior art patent against the invention."""
    patent_info = (
        f"Patent {req.patent.get('patentNumber', 'N/A')}: "
        f"\"{req.patent.get('title', '')}\"\n"
        f"Assignee: {req.patent.get('assignee', 'Unknown')}\n"
        f"Abstract: {req.patent.get('abstract', '')}"
    )
    features = "\n".join(
        f"- {f}" for f in req.decomposition.get("core_features", [])
    )
    user_msg = (
        f"Invention: {req.invention_text}\n\n"
        f"Core Features to evaluate against:\n{features}\n\n"
        f"Prior Art to Evaluate:\n{patent_info}\n\n"
        f"Provide your structured comparison."
    )

    raw = await call_gemini(SYSTEM_EVALUATE, user_msg)
    try:
        parsed = json.loads(clean_json(raw))
    except json.JSONDecodeError:
        raise HTTPException(502, "Failed to parse evaluation response as JSON")

    return parsed


# ── Serve the frontend ───────────────────────────────────────────────────────

FRONTEND_DIR = os.path.join(os.path.dirname(__file__), "..")

@app.get("/")
async def serve_app():
    return FileResponse(os.path.join(FRONTEND_DIR, "eddison-app.html"))

@app.get("/{filename}.html")
async def serve_html(filename: str):
    path = os.path.join(FRONTEND_DIR, f"{filename}.html")
    if os.path.exists(path):
        return FileResponse(path)
    raise HTTPException(404)